import React, { useCallback, useEffect, useState } from 'react'
import { NavBar, Empty, DotLoading, PullToRefresh, InfiniteScroll } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import axios from '../../api/http'

type RegisterItem = {
  id: string | number
  hospital?: string
  department?: string
  doctor?: string
  time?: string
}

function Index() {
  const nav = useNavigate()
  const [loading, setLoading] = useState(false)
  const [list, setList] = useState<RegisterItem[]>([])
  const [pageCode, setPageCode] = useState(1)
  const pageSize = 10
  const [hasMore, setHasMore] = useState(true)
  const [refreshing, setRefreshing] = useState(false)

  const fetchPage = useCallback(async (page:number) => {
    const res:any = await axios.get('/register/list', { params: { pageCode: page, pageSize } })
    const items: RegisterItem[] = (res && (res.data || res.list)) || []
    return Array.isArray(items) ? items : []
  }, [])

  useEffect(() => {
    setLoading(true)
    setHasMore(true)
    setPageCode(1)
    fetchPage(1).then(first => {
      setList(first)
      setHasMore(first.length === pageSize)
    }).finally(()=> setLoading(false))
  }, [fetchPage, pageSize])

  const loadMore = useCallback(async () => {
    if (!hasMore) return
    const nextPage = pageCode + 1
    const next = await fetchPage(nextPage)
    setList(prev => [...prev, ...next])
    setPageCode(nextPage)
    setHasMore(next.length === pageSize)
  }, [fetchPage, hasMore, pageCode, pageSize])

  const onRefresh = useCallback(async () => {
    setRefreshing(true)
    const fresh = await fetchPage(1)
    setList(fresh)
    setPageCode(1)
    setHasMore(fresh.length === pageSize)
    setRefreshing(false)
  }, [fetchPage, pageSize])

  return (
    <div style={{background:'#fff', minHeight:'100vh'}}>
      <NavBar onBack={() => nav(-1)}>我的预约挂号列表</NavBar>

      {loading ? (
        <div style={{display:'flex',alignItems:'center',justifyContent:'center',padding:'40px 0'}}>
          <DotLoading />
          <span style={{marginLeft:8, color:'#999'}}>加载中...</span>
        </div>
      ) : list.length === 0 ? (
        <div style={{paddingTop:'14vh'}}>
          <Empty description='暂无挂号订单' />
        </div>
      ) : (
        <PullToRefresh onRefresh={onRefresh} refreshing={refreshing}>
          <div style={{padding:'0 12px'}}>
            {list.map((item) => (
              <div key={item.id} style={{padding:'12px 0', borderBottom:'1px solid #f2f2f2'}}>
                <div style={{fontSize:15, fontWeight:600}}>{item.hospital || '医院'} · {item.department || '科室'}</div>
                <div style={{marginTop:6, fontSize:12, color:'#888'}}>{item.doctor || '医生'} · {item.time || ''}</div>
              </div>
            ))}
            <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
          </div>
        </PullToRefresh>
      )}
    </div>
  )
}

export default Index
